<?php
/**
 * Created by PhpStorm.
 * User: Yueool
 * Date: 2018/8/10
 * Time: 12:30
 */

namespace common\models;

use Yii;


class Favorite{

    /**
     * 遍历数据表
     */
    public static function trav($cb){
        $db = Yii::$app->db;
        $sql = "SELECT k.* FROM {{%user_practices}} as k";
        $knowledges = $db->createCommand($sql)->queryAll();

        //print_r($knowledges);
        foreach($knowledges as $knowledge){
            $cb($knowledge);
        }
    }

    /**
     * 得到最大的顺序
     * @return mixed
     */
    public static function getLastOrder(){
        $db = Yii::$app->db;
        $sql = "SELECT k.displayorder FROM {{%english}} as k ORDER BY k.displayorder DESC LIMIT 1";
        $order = $db->createCommand($sql)->queryOne();
        return intval($order["displayorder"]);
    }

    /**
     * 得到收藏单词中破冰数量
     */
    public static function getIcebreakingWordCount(){
        $db = Yii::$app->db;
        $sql = "SELECT COUNT(*) FROM en_user_practices AS f LEFT JOIN {{%english}} AS w ON f.id=w.id WHERE w.correct_write>0";
        return $db->createCommand($sql)->queryScalar();//破冰单词量
    }

    /**
     * 得到收藏单词中破冰数量
     */
    public static function getGraduatedWordCount(){
        $db = Yii::$app->db;
        $sql = "SELECT COUNT(*) FROM en_user_practices AS f LEFT JOIN {{%english}} AS w ON f.id=w.id WHERE w.correct_write>15";
        return $db->createCommand($sql)->queryScalar();//破冰单词量
    }

    /**
     * 交换两条数据的顺序
     * @param $id1
     * @param $id2
     */
    public static function exchange($id1, $id2){

        $db = Yii::$app->db;

        $sql = 'UPDATE {{%user_practices}} AS a, {{%user_practices}} AS b SET a.displayorder=b.displayorder, b.displayorder=a.displayorder';
        $sql = $sql." WHERE a.id=$id1 AND b.id=$id2";
        //echo $db->createCommand($sql)->getRawSql();exit;

        try{
            $line = $db->createCommand($sql)->execute();
        }catch(\Exception $e){
            throw new \RuntimeException("SQL执行错误:".$e->getFile()." ".$e->getLine()." ".$e->getMessage());
        }

        if($line == 2){
            return true;
        }else{
            throw new \RuntimeException("交换失败");
        }

    }

    public static function getSqlCondition($fav, $as = ''){
        $fav = intval($fav);
        $as = (empty($as)) ? '' : $as.".";

        $condition = "";
        if($fav == 1){
            return " AND f.".$as.$tags[0]."=1";
        }else if(count($tags) == 1){
            return " AND ".$as.$tags[0]."=1";
        }else if(count($tags) > 1){
            foreach($tags as $tag){
                $condition .= " OR ".$as.$tag."=1";
            }
            $condition = preg_replace('/^ OR /', '', $condition);
            return " AND (".$condition.")";
        }
    }

}